<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import type { TreeProps } from "ant-design-vue";
import { useGetDocListTree } from "@/composables";
import { useRoute } from "vue-router";
import type { Content } from "@/types/content";
import { getContentById } from "@/services/content";

const route = useRoute();
const fieldNames: TreeProps["fieldNames"] = {
  children: "children",
  title: "name",
  key: "id",
};
const selectedKeys = ref<number[]>([]);
const content = ref<Content>({});

// composable
const { docListTreeRemoveParent, getDocListTree } = useGetDocListTree(
  Number(route.query.ebookId as string),
);

// 加载列表
const loadList = async () => {
  await getDocListTree();
};

watch(selectedKeys, async () => {
  if (selectedKeys.value[0] !== undefined) {
    const currentKey = selectedKeys.value[0];
    const res = await getContentById(currentKey);
    content.value.content = res.content.content;
  }
});

onMounted(async () => {
  await loadList();
  // 默认选择第一个
  if (docListTreeRemoveParent.value.length > 0)
    selectedKeys.value = [docListTreeRemoveParent.value[0].id!];
});
</script>
<template>
  <a-layout>
    <a-layout-content
      :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <h3 v-if="docListTreeRemoveParent.length === 0">对不起，找不到相关文档</h3>
      <a-row>
        <a-col :span="6">
          <a-tree
            v-if="docListTreeRemoveParent.length > 0"
            v-model:selectedKeys="selectedKeys"
            :tree-data="docListTreeRemoveParent"
            :field-names="fieldNames"
            :defaultExpandAll="true"
          >
          </a-tree>
        </a-col>
        <a-col :span="18"> <div class="editor-content-view" v-html="content?.content"></div></a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>
<style></style>
